﻿CREATE PROCEDURE [maint].[CheckWindow]
@DbName [sysname], @CheckPointDate DATETIME=NULL, @IsOpen BIT OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0

	IF(@CheckPointDate IS NULL)
		SET @CheckPointDate = GETDATE()

	SET DATEFIRST 1

	DECLARE @Hour int
	SET @Hour = DATEPART(hh, @CheckPointDate) + 1
	
	SELECT
		@IsOpen =
			(CASE
				WHEN ([MaintenanceWindow] & POWER(2, @Hour - (CASE WHEN @Hour = 1 THEN 0 ELSE 1 END))) = 0 THEN 0
				ELSE 1
			END)
	FROM [config].[DbMaintenance]
	WHERE ([DbName] = @DbName)
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
		GOTO ERROR_HANDLER
		
	IF(@IsOpen = 0)
		PRINT 'Maintenance window is closed. No database maintenance could be performed.'

	GOTO EXIT_PROC

ERROR_HANDLER:
	IF(@RC = 0)
		SET @RC = @ERROR

EXIT_PROC:
	RETURN(@RC)
END